<?php

namespace app\beautiful\model\goods;

use app\beautiful\model\mall\GoodsModel;
use app\common\model\CommonModel;
use think\facade\Db;


class GoodsGroupModel extends CommonModel{

    protected  $name = 'beautiful_goods_group';

    protected  $pk   = 'goods_group_id';
    /**
     * 模型写入前事件（钩子函数）
     */
    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public function groupDetail(){

        return  $this->hasMany(GoodsGroupDetailModel::class,'goods_group_id','goods_group_id');

    }
    public static function up($data,$where){
        $res=self::update($data,$where);
        return $res;
    }

    public static function list($where,$order,$page=0,$limit=0,$field='*'){
        $query = Db::name('beautiful_goods_group')
            ->where(['is_delete'=>0])
            ->when(isset($where['goods_id']),function ($query) use ($where){
                $query->where(['goods_id'=>$where['goods_id']]);
            })
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['shop_id'=>$where['shop_id']]);
            })
            ->field($field);

        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->field($field)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $return = GoodsGroupDetailModel::list(['goods_group_id'=>$v['goods_group_id']],['add_time'=>'asc']);
                $v['groupDetail'] = $return['list'];
            }
        }

        return compact('count','list');



    }
}

